import functools
import logging
import traceback
import asyncio
from typing import Callable, Any

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('contentforge.log', encoding='utf-8'),
        logging.StreamHandler()
    ]
)

logger = logging.getLogger(__name__)

def log_method(level: str = 'info'):
    """
    支持同步和异步方法的日志装饰器
    
    Args:
        level (str): 日志级别，默认为 'info'
    """
    def decorator(func: Callable):
        @functools.wraps(func)
        async def async_wrapper(*args, **kwargs):
            try:
                logger.log(
                    getattr(logging, level.upper()), 
                    f"调用方法: {func.__name__}"
                )
                result = await func(*args, **kwargs)
                return result
            except Exception as e:
                logger.error(f"方法 {func.__name__} 执行失败: {str(e)}")
                logger.error(traceback.format_exc())
                raise
        
        @functools.wraps(func)
        def sync_wrapper(*args, **kwargs):
            try:
                logger.log(
                    getattr(logging, level.upper()), 
                    f"调用方法: {func.__name__}"
                )
                result = func(*args, **kwargs)
                return result
            except Exception as e:
                logger.error(f"方法 {func.__name__} 执行失败: {str(e)}")
                logger.error(traceback.format_exc())
                raise
        
        # 根据函数类型返回不同的包装器
        return async_wrapper if asyncio.iscoroutinefunction(func) else sync_wrapper
    
    return decorator 